package com.cans.lightning.base.service.impl;

import com.cans.lightning.base.dto.BaseDto;
import com.cans.lightning.base.entity.BaseEntity;
import com.cans.lightning.base.mapper.IBaseMapper;
import com.cans.lightning.base.service.api.IBaseService;
import org.beetl.sql.mapper.BaseMapper;

import java.util.Date;
import java.util.List;

/**
 * 基础服务实现
 *
 * @author shencan
 * @date 2020/6/14 21:06
 */
public abstract class BaseServiceImpl<T extends BaseEntity, D extends BaseDto<ID>, ID> implements IBaseService<T, D, ID> {

    @Override
    public void saveOrUpdateDto(D d) {
        T t = getMapperImpl().toEntity(d);
        Date date = new Date();
        t.setCreateTime(date);
        t.setLastChangeTime(date);
        getDaoImpl().upsert(t);
    }

    @Override
    public void saveOrUpdate(T t) {
        getDaoImpl().upsert(t);
    }

    @Override
    public void insertList(List<T> t) {
        getDaoImpl().insertBatch(t);
    }

    @Override
    public void insertDtoList(List<D> dtoList) {
        getDaoImpl().insertBatch(this.getMapperImpl().toEntitys(dtoList));
    }


    /**
     * 删除
     *
     * @param t
     */
    @Override
    public void delete(T t) {
        getDaoImpl().deleteById(t.getId());
    }

    /**
     * 通过ID获取 Engity
     *
     * @param id
     * @return
     */
    @Override
    public T getById(ID id) {
        return getDaoImpl().single(id);
    }

    @Override
    public D getDtoById(ID id) {
        return getMapperImpl().toDto(getById(id));
    }


    @Override
    public List<T> getByIds(List<ID> ids) {
        return getDaoImpl().selectByIds(ids);
    }

    /**
     * 删除
     *
     * @param id
     */
    @Override
    public void deleteById(ID id) {
        getDaoImpl().deleteById(id);
    }

    @Override
    public void deletes(ID[] ids) {
        for (ID id : ids) {
            this.getDaoImpl().deleteById(id);
        }
    }

    /**
     * 查询全部
     *
     * @return
     */
    @Override
    public List<T> findAll() {
        return getDaoImpl().all();
    }

    @Override
    public List<D> findAllToDto() {
        return getMapperImpl().toDtos(findAll());
    }

    @Override
    public D toDto(T t) {
        return getMapperImpl().toDto(t);
    }

    @Override
    public T toEntity(D d) {
        return getMapperImpl().toEntity(d);
    }

    /**
     * 获取DAO实现
     *
     * @return
     */
    public abstract BaseMapper<T> getDaoImpl();

    /**
     * 获取DAO实现
     *
     * @return
     */
    public abstract IBaseMapper<T, D, ID> getMapperImpl();

}
